import 'dart:async';

import 'package:star_author/views/stream/stream_rtc_top.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../event_bus/global_event_bus.dart';
import '../../event_bus/socket_subscription_event.dart';

class MuteWidget extends StatefulWidget {
  const MuteWidget({Key? key}) : super(key: key);

  @override
  State<MuteWidget> createState() => _MuteWidgetState();
}

class _MuteWidgetState extends State<MuteWidget> {
  var mute = {};
  bool showCome = false;
  int count = 3;

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  late Timer? timer = null;

  ban(map) {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      mute = map;
      showCome = true;
      count = 3;
      update(() {});
      timer = Timer.periodic(Duration(seconds: 1), (_timer) {
        if (count <= 0) {
          _timer.cancel();
          timer?.cancel();
          update(() {
            showCome = false;
          });
        }
        count--;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<SocketSubscriptionEvent>(
      builder: (BuildContext context,
          AsyncSnapshot<SocketSubscriptionEvent> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            break;
          case ConnectionState.waiting:
            break;
          case ConnectionState.active:
            SocketSubscriptionEvent arg =
                snapshot.data as SocketSubscriptionEvent;
            var message = arg.message['message'] ?? {};
            if (message != null) {
              String action = message['action'] ?? "";
              if (action == "ban_user") {
                ban(message);
              } else if (action == "unban_user") {
                ban(message);
                // CustomToast.show("当前主播已下播");
              }
              int users_count = message['users_count'] ?? 0;
              int view_users_count = message['view_users_count'] ?? 0;
              valueNotifier.setCount(view_users_count);
            }
            break;
          case ConnectionState.done:
            // TODO: Handle this case.
            break;
        }
        return Container(
          child: Offstage(
            child: Container(
              margin: EdgeInsets.symmetric(
                horizontal: 12.w,
              ),
              constraints:
                  BoxConstraints(minWidth: 1, maxWidth: Get.width * 0.7),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.0.w),
                  gradient: LinearGradient(colors: [
                    Color(0x4DFF8F4F),
                    Color(0x00FFD48D),
                  ])),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  //左侧是图片
                  Container(
                    margin: EdgeInsets.only(right: 3.w),
                    child: buildCircleCover(
                        size: 16.w, cover: mute['user_avatar'] ?? ""),
                  ),
                  //右侧是文字自适应
                  Container(
                    child: Container(
                      constraints: BoxConstraints(
                          minWidth: 1, maxWidth: Get.width * 0.5),
                      child: Text(
                        '${mute['user_nickname'] ?? ""}',
                        style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w500),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                  ),
                  Container(
                    child: Container(
                      constraints: BoxConstraints(
                          minWidth: 1, maxWidth: Get.width * 0.5),
                      child: Text(
                        ' ${mute['action'] == "ban_user" ? "被禁言" : "取消禁言"}',
                        style: TextStyle(
                            fontSize: 12.sp,
                            color: Color(0xFFFEBA07),
                            fontWeight: FontWeight.w500),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                  )
                ],
              ),
              padding: EdgeInsets.only(
                  right: 14.w, left: 8.w, top: 5.w, bottom: 5.w),
            ),
            offstage: !showCome || mute.isEmpty,
          ),
        );
      },
      stream: GlobalEventBus().bus.on<SocketSubscriptionEvent>(),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    timer?.cancel();
  }
}
